package com.pro01.backend.controller;

import com.pro01.backend.dto.LoginResponseDTO;
import com.pro01.backend.mapper.UserInviteMapper;
import com.pro01.backend.mapper.UserMapper;
import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.pojo.User;
import com.pro01.backend.pojo.UserPromotion;
import com.pro01.backend.service.ConnectionStatusService;
import com.pro01.backend.service.EmailService;
import com.pro01.backend.service.UserPromotionService;
import com.pro01.backend.service.UserService;
import com.pro01.backend.utils.JwtUtil;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserInviteMapper userInviteMapper;
    @Autowired
    private EmailService emailService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserPromotionService userPromotionService;
    @Autowired
    private ConnectionStatusService connectionStatusService;

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/info")
    public Result<?> getUserInfo(HttpServletRequest request) {
        // 从 Token 获取 userId
//        String token = request.getHeader("Authorization");
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        if (claims == null) {
//            return Result.error("无效的 Token，请重新登录");
//        }

        // 查询用户信息
        //Long userId = ((Number) claims.get("id")).longValue();
        Long userId = TokenUtil.getUserId(request);
        User user = userService.getUserSafeInfoById(userId);
        return user != null ? Result.success(user) : Result.error("用户不存在");
    }


    /**
     * 更新当前用户信息
     */
    @PutMapping("/update")
    public Result<User> updateUser(HttpServletRequest request, @RequestBody User user) {
        // 只能修改自己的信息
//        String token = request.getHeader("Authorization");
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        if (claims == null) {
//            return Result.error("无效的 Token，请重新登录");
//        }
//
//        Long userId = ((Number) claims.get("id")).longValue();
        Long userId = TokenUtil.getUserId(request);
        user.setId(userId);

        int result = userService.updateUser(user);
        return result > 0 ? Result.success(user) : Result.error("更新用户失败");
    }


    /**
     * 发送邮箱验证码
     */
//    @PostMapping("/sendEmailCode")
//    public Result<Void> sendEmailCode(@RequestParam String email) {
//        return emailService.sendEmailCode(email) ? Result.success() : Result.error("邮件发送失败");
//    }
    @PostMapping("/sendEmailCode")
    public Result<Void> sendEmailCode(@RequestBody Map<String, String> requestBody) {
        String email = requestBody.get("email");
        if (email == null || email.isEmpty()) {
            return Result.error("邮箱不能为空");
        }
        return emailService.sendEmailCode(email) ? Result.success() : Result.error("邮件发送失败");
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody Map<String, String> requestBody) {
        try {
            String username = requestBody.get("username");
            String password = requestBody.get("password");
            String email = requestBody.get("email");
            String inviteCode = requestBody.get("inviteCode");
            String emailCode = requestBody.get("emailCode");

            return userService.register(username, password, email, inviteCode, emailCode)
                    ? Result.success("注册成功") : Result.error("注册失败");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登录
     */

//    @PostMapping("/login")
//    public Result<LoginResponseDTO> login(@RequestBody Map<String, String> requestBody) {
//        try {
//            String username = requestBody.get("username");
//            String password = requestBody.get("password");
//
//            // 调用 service 返回 token 和用户对象
//            Map.Entry<String, String> tokenAndRole = userService.login(username, password);
//            String token = tokenAndRole.getKey();
//            String role = tokenAndRole.getValue();
//
//            return Result.success(new LoginResponseDTO(token, role));
//        } catch (RuntimeException e) {
//            return Result.error(e.getMessage());
//        }
//    }

    @PostMapping("/login")
    public Result<LoginResponseDTO> login(@RequestBody Map<String, String> requestBody) {
        try {
            String username = requestBody.get("username");
            String password = requestBody.get("password");

            LoginResponseDTO loginResponse = userService.login(username, password);
            return Result.success(loginResponse);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }


    /**
     * 用户刷新自己的贡献值和等级
     */
    @PostMapping("/refresh-my-credit")
    public Result<?> refreshMyCredit(HttpServletRequest request) {
//        String token = request.getHeader("Authorization");
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        if (claims == null) {
//            return Result.error("未授权，请先登录");
//        }
//
//        Long userId = ((Number) claims.get("id")).longValue();
        Long userId = TokenUtil.getUserId(request);
        userService.refreshCreditAndLevel(userId);
        return Result.success("你的贡献值和等级已刷新！");
    }

    @GetMapping("/downloads/remaining")
    public Result<Integer> getRemainingDownloads(HttpServletRequest request) {
        try {
//            String token = request.getHeader("Authorization");
//            Map<String, Object> claims = JwtUtil.parseToken(token);
//            if (claims == null) {
//                return Result.error("未授权");
//            }
//            Long userId = ((Number) claims.get("id")).longValue();

            Long userId = TokenUtil.getUserId(request);
            int remaining = userService.getTodayRemainingDownloads(userId);
            return Result.success(remaining);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询贡献值前10的用户
     */
    @GetMapping("/leaderboard/credit")
    public Result<Map<String, Object>> getCreditLeaderboard(HttpServletRequest request) {
        try {
            List<User> topUsers = userMapper.getTopUsersByCredit(10);  // 前 10 名
            List<Map<String, Object>> rankings = new ArrayList<>();

            for (User user : topUsers) {
                Map<String, Object> entry = new HashMap<>();
                entry.put("username", user.getUsername());
                entry.put("credit", user.getCredit());
                entry.put("level", user.getLevel());
                rankings.add(entry);
            }

            // 自己的排名（如果登录了）
            Integer yourRank = null;
//            String token = request.getHeader("Authorization");
//            if (token != null) {
//                Map<String, Object> claims = JwtUtil.parseToken(token);
//                if (claims != null) {
//                    Long userId = ((Number) claims.get("id")).longValue();
//                    yourRank = userMapper.getRankByCredit(userId);
//                }
//            }

            try {
                Long userId = TokenUtil.getUserId(request); // ✅ 会抛异常，说明未登录
                yourRank = userMapper.getRankByCredit(userId);
            } catch (Exception ignored) {
                // 未登录就跳过，不设置 yourRank
            }
            Map<String, Object> result = new HashMap<>();
            result.put("rankings", rankings);
            result.put("yourRank", yourRank); // 可能是 null，如果未登录
            return Result.success(result);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }


    /**
     * 查询准分享率前10的用户
     */
    @GetMapping("/leaderboard/ratio")
    public Result<Map<String, Object>> getRatioLeaderboard(HttpServletRequest request) {
        try {
            List<User> topUsers = userMapper.getTopUsersByRatio(10);  // 前 10 名
            List<Map<String, Object>> rankings = new ArrayList<>();

            for (User user : topUsers) {
                Map<String, Object> entry = new HashMap<>();
                entry.put("username", user.getUsername());
                entry.put("virtualRatio", user.getVirtualRatio());
                entry.put("level", user.getLevel());
                rankings.add(entry);
            }

            // 自己的排名（如果登录了）
            Integer yourRank = null;
//            String token = request.getHeader("Authorization");
//            if (token != null) {
//                Map<String, Object> claims = JwtUtil.parseToken(token);
//                if (claims != null) {
//                    Long userId = ((Number) claims.get("id")).longValue();
//                    yourRank = userMapper.getRankByRatio(userId);
//                }
//            }

            try {
                Long userId = TokenUtil.getUserId(request); // ✅ 会抛异常，说明未登录
                yourRank = userMapper.getRankByCredit(userId);
            } catch (Exception ignored) {
                // 未登录就跳过，不设置 yourRank
            }
            Map<String, Object> result = new HashMap<>();
            result.put("rankings", rankings);
            result.put("yourRank", yourRank); // 可能是 null，如果未登录
            return Result.success(result);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 模糊查询用户
     */
    /*
    @GetMapping("/search")
    public Result<List<User>> searchUsers(
            @RequestParam("keyword") String keyword,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 🔥 防止有人传超大 pageSize
            if (pageSize > 50) {
                pageSize = 50;
            }

            List<User> users = userService.searchUsersByUsername(keyword, pageNum, pageSize);
            return Result.success(users);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("搜索失败：" + e.getMessage());
        }
    }
     */
    @GetMapping("/search")
    public Result<PageResult<User>> searchUsers(
            @RequestParam("keyword") String keyword,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            if (pageSize > 50) {
                pageSize = 50;
            }

            PageResult<User> result = userService.searchUsersByUsernameWithTotal(keyword, pageNum, pageSize);
            return Result.success(result);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("搜索失败：" + e.getMessage());
        }
    }

    @GetMapping("/promotions/my-rewards")
    public Result<PageResult<UserPromotion>> getMyPromotionRewards(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        try {
//            String token = request.getHeader("Authorization");
//            Map<String, Object> claims = JwtUtil.parseToken(token);
//            if (claims == null) {
//                return Result.error("未登录，请先登录！");
//            }
//
//            Long userId = ((Number) claims.get("id")).longValue();

            Long userId = TokenUtil.getUserId(request);
            PageResult<UserPromotion> pageResult = userPromotionService.getMyPromotionRewards(userId, pageNum, pageSize);
            return Result.success(pageResult);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }


    /**
     * 修改密码
     */
//    @PutMapping("/changePassword")
//    public Result<?> changePassword(HttpServletRequest request, @RequestBody Map<String, String> requestBody) {
//        // 获取 Token 并解析用户信息
////        String token = request.getHeader("Authorization");
////        Map<String, Object> claims = JwtUtil.parseToken(token);
////        if (claims == null) {
////            return Result.error("无效的 Token，请重新登录");
////        }
//
//        // 获取用户 ID
//        //Long userId = ((Number) claims.get("id")).longValue();
//        Long userId = TokenUtil.getUserId(request);
//        // 获取旧密码和新密码
//        String oldPassword = requestBody.get("oldPassword");
//        String newPassword = requestBody.get("newPassword");
//
//        // 执行密码修改
//        boolean success = userService.changePassword(userId, oldPassword, newPassword);
//        return success ? Result.success("密码修改成功") : Result.error("密码修改失败");
//    }
    @PutMapping("/changePassword")
    public Result<?> changePassword(HttpServletRequest request, @RequestBody Map<String, String> requestBody) {
        Long userId = TokenUtil.getUserId(request);

        // 获取请求参数
        String inputUsername = requestBody.get("username");
        String oldPassword = requestBody.get("oldPassword");
        String newPassword = requestBody.get("newPassword");

        // 查询真实用户名并验证
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (!user.getUsername().equals(inputUsername)) {
            return Result.error("用户名不匹配，禁止修改密码");
        }

        // 执行密码修改
        boolean success = userService.changePassword(userId, oldPassword, newPassword);
        return success ? Result.success("密码修改成功") : Result.error("密码修改失败");
    }

    // 修改用户名
    @PutMapping("/update-username")
    public Result<?> updateUsername(@RequestBody Map<String, String> requestBody,
                                    HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            String newUsername = requestBody.get("newUsername");

            boolean success = userService.updateUsername(userId, newUsername);
            return success ? Result.success("用户名修改成功") : Result.error("用户名修改失败");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 连接性检测
    @GetMapping("/my-status")
    public Result<Boolean> getMyConnectionStatus(HttpServletRequest request) {
        Long userId = TokenUtil.getUserId(request);
        boolean online = connectionStatusService.isUserOnline(userId);
        return Result.success(online);
    }


    /**
     * 用户退出登录
     */
    @PostMapping("/logout")
    public Result<?> logout(HttpServletRequest request) {
        TokenUtil.getUserId(request); // 校验 token 是否有效
        return Result.success("退出登录成功");
    }

}
